/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View.components;

import Model.Cliente;
import Presenter.ClientePresenter;
import Principals.Validadores;
import View.ventas.Frm_RegistrarPedido;
import javax.swing.table.*;
import java.awt.Dimension;
import java.awt.Point;
import java.util.*;
import javax.swing.*;

/**
 *
 * @author walter
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
public class PopUpBuscarCliente extends javax.swing.JDialog {

    private JDesktopPane pnl;
    private List<Cliente> lstCliente;
    private DefaultTableModel mdlBuscarCliente;
    private Cliente cliente;
    private String errorMsg;
    private Validadores val = new Validadores();

    public PopUpBuscarCliente(JFrame parent) {
        super(parent, true);
        if (parent != null) {
            Dimension parentSize = parent.getSize();
            Point p = parent.getLocation();
            setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
        }
        initComponents();
        val.desactivarAccionPegar(txtNombres);
        val.desactivarAccionPegar(txtApPaterno);
        val.desactivarAccionPegar(txtApMaterno);
        val.desactivarAccionPegar(txtDocId);        
        tblBuscarCliente.getTableHeader().setReorderingAllowed(false);
        mdlBuscarCliente = new DefaultTableModel();
        this.pack();
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        pnl = new JDesktopPane() ;
        pnlBuscarCliente = new javax.swing.JPanel();
        lblNombres = new javax.swing.JLabel();
        lblApPaterno = new javax.swing.JLabel();
        lblApMaterno = new javax.swing.JLabel();
        txtNombres = new javax.swing.JTextField();
        txtApPaterno = new javax.swing.JTextField();
        txtApMaterno = new javax.swing.JTextField();
        lblDocId = new javax.swing.JLabel();
        txtDocId = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JToggleButton();
        pnlResultadosCliente = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblBuscarCliente = new javax.swing.JTable();
        jToolBar1 = new javax.swing.JToolBar();
        btnToolNuevo = new javax.swing.JButton();
        btnToolModificar = new javax.swing.JButton();
        btnToolGuardar = new javax.swing.JButton();
        btnToolEliminar = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        btnToolLimpiar = new javax.swing.JButton();
        btnToolBuscar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnToolCancelar = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();

        pnlBuscarCliente.setBorder(javax.swing.BorderFactory.createTitledBorder("Búsqueda"));

        lblNombres.setText("Nombres:");

        lblApPaterno.setText("Apellido Paterno:");

        lblApMaterno.setText("Apellido Materno:");

        txtNombres.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombresKeyTyped(evt);
            }
        });

        txtApPaterno.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtApPaternoKeyTyped(evt);
            }
        });

        txtApMaterno.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtApMaternoKeyTyped(evt);
            }
        });

        lblDocId.setText("Doc. de Identidad:");

        txtDocId.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDocIdKeyTyped(evt);
            }
        });

        btnBuscar.setText("Buscar");
        btnBuscar.setAutoscrolls(true);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBuscarClienteLayout = new javax.swing.GroupLayout(pnlBuscarCliente);
        pnlBuscarCliente.setLayout(pnlBuscarClienteLayout);
        pnlBuscarClienteLayout.setHorizontalGroup(
            pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBuscarClienteLayout.createSequentialGroup()
                .addGroup(pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(pnlBuscarClienteLayout.createSequentialGroup()
                        .addGroup(pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblApPaterno)
                            .addComponent(lblNombres))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtApPaterno, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                            .addComponent(txtNombres))
                        .addGap(26, 26, 26)
                        .addGroup(pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(pnlBuscarClienteLayout.createSequentialGroup()
                                .addComponent(lblDocId)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtDocId))
                            .addGroup(pnlBuscarClienteLayout.createSequentialGroup()
                                .addComponent(lblApMaterno)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtApMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pnlBuscarClienteLayout.setVerticalGroup(
            pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBuscarClienteLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblApPaterno)
                    .addComponent(txtApPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblApMaterno)
                    .addComponent(txtApMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlBuscarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombres)
                    .addComponent(txtNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDocId)
                    .addComponent(txtDocId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnBuscar)
                .addContainerGap())
        );

        pnlResultadosCliente.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));

        tblBuscarCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id Cliente", "Nombres", "Ap. Paterno", "Ap. Materno", "Tipo Doc.Id.", "Doc. Ident.", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblBuscarCliente.addMouseListener( new java.awt.event.MouseAdapter(){
            @Override
            public void mouseClicked( java.awt.event.MouseEvent evt ){
                tblBuscarClienteMouseClicked( evt ) ;
            }
        });
        jScrollPane1.setViewportView(tblBuscarCliente);

        javax.swing.GroupLayout pnlResultadosClienteLayout = new javax.swing.GroupLayout(pnlResultadosCliente);
        pnlResultadosCliente.setLayout(pnlResultadosClienteLayout);
        pnlResultadosClienteLayout.setHorizontalGroup(
            pnlResultadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)
        );
        pnlResultadosClienteLayout.setVerticalGroup(
            pnlResultadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
        );

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setBorderPainted(false);

        btnToolNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Nuevo.png"))); // NOI18N
        btnToolNuevo.setFocusable(false);
        btnToolNuevo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolNuevo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolNuevoActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolNuevo);

        btnToolModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Editar.png"))); // NOI18N
        btnToolModificar.setFocusable(false);
        btnToolModificar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolModificar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolModificarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolModificar);

        btnToolGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Guardar.png"))); // NOI18N
        btnToolGuardar.setEnabled(false);
        btnToolGuardar.setFocusable(false);
        btnToolGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnToolGuardar);

        btnToolEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Eliminar.png"))); // NOI18N
        btnToolEliminar.setEnabled(false);
        btnToolEliminar.setFocusable(false);
        btnToolEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolEliminarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolEliminar);
        jToolBar1.add(jSeparator3);

        btnToolLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Limpiar.png"))); // NOI18N
        btnToolLimpiar.setFocusable(false);
        btnToolLimpiar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolLimpiar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolLimpiarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolLimpiar);

        btnToolBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Buscar.png"))); // NOI18N
        btnToolBuscar.setFocusable(false);
        btnToolBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolBuscarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolBuscar);
        jToolBar1.add(jSeparator1);

        btnToolCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/botones/Cancelar.png"))); // NOI18N
        btnToolCancelar.setFocusable(false);
        btnToolCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnToolCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnToolCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnToolCancelarActionPerformed(evt);
            }
        });
        jToolBar1.add(btnToolCancelar);
        jToolBar1.add(jSeparator2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(pnl);
        pnl.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlBuscarCliente, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlResultadosCliente, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 10, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlBuscarCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlResultadosCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        this.add( pnl ) ;
    }// </editor-fold>                      

    private void btnToolLimpiarActionPerformed(java.awt.event.ActionEvent evt) {
        limpiar();
    }

    private void btnToolModificarActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void btnToolBuscarActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void btnToolCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        cerrar();
    }

    private void btnToolEliminarActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {
         try{
            String nombres = txtNombres.getText();
            String apPaterno = txtApPaterno.getText();
            String apMaterno = txtApMaterno.getText();
            String docIdentidad = txtDocId.getText();
            lstCliente = ClientePresenter.buscarCliente(nombres, apPaterno, apMaterno, docIdentidad);

            mdlBuscarCliente.setNumRows(0);
            mdlBuscarCliente = (DefaultTableModel) tblBuscarCliente.getModel();

            for (int i = 0; i < lstCliente.size(); i++) {
                Cliente c = lstCliente.get(i);            
                String estado="";
                switch (c.getEstado()){
                    case 0: estado="Inactivo"; break;
                    case 1: estado="Activo"; break;
                }            
                Object[] row = new Object[]{c.getIdCliente(), c.getNombres(), c.getApellidoPaterno(), c.getApellidoMaterno(), "DNI", c.getNroDocumento(),estado};
                mdlBuscarCliente.insertRow(i, row);
            }
            tblBuscarCliente.setVisible(true);
            JOptionPane.showMessageDialog(this, "Se encontraron " + mdlBuscarCliente.getRowCount() + " coincidencias");
        }
        catch (Exception e){
            JOptionPane.showMessageDialog(this, "No se pudo realizar la transacción.");
            System.out.println("MENSAJE DE ERROR:"+e);
        }  }

    private void btnToolNuevoActionPerformed(java.awt.event.ActionEvent evt) { // <----------
        this.setVisible(false);
        new PopUpNuevoCliente((Index) this.getParent());
    }

    private void tblBuscarClienteMouseClicked(java.awt.event.MouseEvent evt) {
        if (evt.getClickCount() == 2) {
            if (this.tblBuscarCliente.getSelectedRow() == -1) {
                errorMsg = "Por favor seleccione un cliente.";
                JOptionPane.showMessageDialog(this, errorMsg);
            } else {
                int i = this.tblBuscarCliente.getSelectedRow();
                cliente = this.lstCliente.get(i);

                 if(cliente.getEstado()==0){
                    errorMsg = "Por favor seleccione un cliente activo.";
                    JOptionPane.showMessageDialog(this, errorMsg);
                }
                 else{
                    Index p = (Index) (this.getParent());
                    if ((p.getContainer().getClass().toString().equals("class View.ventas.Frm_RegistrarPedido"))) {
                        try {
                            this.setVisible(false);
                            Frm_RegistrarPedido owner = (Frm_RegistrarPedido) p.getContainer();
                            owner.actualizarDatosCliente(cliente);
                        } catch (Exception e) {
                        }
                    }
                 }
            }
        }
    }

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {
    }

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        cerrar();
    }

    private void txtApPaternoKeyTyped(java.awt.event.KeyEvent evt) {                                      
        val.validaCaracteresRaros(evt);
        val.validaMaxSize(evt, 20, txtApPaterno.getText());
        txtApPaterno.setTransferHandler(null);
    }                                     

    private void txtApMaternoKeyTyped(java.awt.event.KeyEvent evt) {                                      
        val.validaCaracteresRaros(evt);
        val.validaMaxSize(evt, 20, txtApMaterno.getText());
        txtApMaterno.setTransferHandler(null);
    }                                     

    private void txtNombresKeyTyped(java.awt.event.KeyEvent evt) {                                    
        val.validaCaracteresRaros(evt);
        val.validaMaxSize(evt, 20, txtNombres.getText());
        txtNombres.setTransferHandler(null);
    }                                   

    private void txtDocIdKeyTyped(java.awt.event.KeyEvent evt) {                                  
        val.validaSoloNumeros(evt);
        val.validaMaxSize(evt, 8, txtDocId.getText());
        txtDocId.setTransferHandler(null);
    }

    private void cerrar() {
        this.setVisible(false);
    }

    private void limpiar() {
        txtApMaterno.setText("");
        txtApPaterno.setText("");
        txtNombres.setText("");
        txtDocId.setText("");
        mdlBuscarCliente.setNumRows(0);
        mdlBuscarCliente = (DefaultTableModel) tblBuscarCliente.getModel();
    }
    // Variables declaration - do not modify
    private javax.swing.JToggleButton btnBuscar;
    private javax.swing.JButton btnToolBuscar;
    private javax.swing.JButton btnToolCancelar;
    private javax.swing.JButton btnToolEliminar;
    private javax.swing.JButton btnToolGuardar;
    private javax.swing.JButton btnToolLimpiar;
    private javax.swing.JButton btnToolModificar;
    private javax.swing.JButton btnToolNuevo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lblApMaterno;
    private javax.swing.JLabel lblApPaterno;
    private javax.swing.JLabel lblDocId;
    private javax.swing.JLabel lblNombres;
    private javax.swing.JPanel pnlBuscarCliente;
    private javax.swing.JPanel pnlResultadosCliente;
    private javax.swing.JTable tblBuscarCliente;
    private javax.swing.JTextField txtApMaterno;
    private javax.swing.JTextField txtApPaterno;
    private javax.swing.JTextField txtDocId;
    private javax.swing.JTextField txtNombres;
    // End of variables declaration
}
